// pages/order/addplan/addplan.js
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
const app = getApp();
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		goodsOwnerUserId: "",
		goodsOwnerUserName: "",
		receiptTime: "",
		details: [],//采购
		typeList: [],
		showPicker: false,
		showPickerCrop: false,
		showPickerType: false,
		currentDate: '',
		minDate: new Date().getTime(),
		list: [],//多选列表
		result: [],//多选选中的结果
		cropList: [],
		needList: [],
		remarks: '',
		id: '',//接收跳转接收过来id
		type: '',//接受传递过来的页面类型
		farmerList:[],//接收选择的农户列表
		packList: [],//包装列表
		flag:false

	},
	fahuo() {
		const id = this.data.id;
		Dialog.confirm({
			context: this,
			title: '提示',
			message: '确定完成计划吗？',
		})
			.then(() => {
				wx.showLoading({
					title: '完成中...',
				})
				wx.$apis.completePurchase({
					ids: [id],
				}).then(res => {
					this.onPullDownRefresh();
					if (!res.data) {
						return wx.showToast({
							title: '操作失败，请稍后再试~',
							icon: 'none',
							duration: 2000
						})
					}
					wx.showToast({
						title: '操作成功',
						icon: 'success',
						duration: 1000
					})
					wx.setStorage({
						key: "back",
						data: true,
						success: function () {
								wx.navigateBack(); //返回上一个页面
						}
					})

				})
			})
			.catch(() => {
			});

	},
	quxiao() {
		const id = this.data.id;
		Dialog.confirm({
			context: this,
			title: '提示',
			message: '确定取消计划吗？',
		})
			.then(() => {
				wx.showLoading({
					title: '完成中...',
				})
				wx.$apis.cancelPurchase(id).then(res => {
					this.onPullDownRefresh();
					if (!res.data) {
						return wx.showToast({
							title: '操作失败，请稍后再试~',
							icon: 'none',
							duration: 2000
						})
					}
					wx.showToast({
						title: '操作成功',
						icon: 'success',
						duration: 1000
					})
					wx.setStorage({
						key: "back",
						data: true,
						success: function () {
								wx.navigateBack(); //返回上一个页面
						}
					})

				})
			})
			.catch(() => {
			});
	},
	//采购单详情 getOrderInfo
	getDetail(id) {
		wx.$apis.getOrderInfo(id).then(res => {
			wx.hideLoading();
			if (res.data) {
				let result = res.data.details.map(item => {
					return item.cropName
				})
				this.setData({
					goodsOwnerUserName: res.data.goodsOwnerName,
					goodsOwnerUserId: res.data.goodsOwnerUserId,
					receiptTime: res.data.receiptTime.substr(0, 10),
					result: result,
					cropList: res.data.details,
					remarks: res.data.remarks,
					farmerList:res.data.farmerUsers,
					packList:res.data.packs,
				})
			}
		}).catch(err => {
			wx.hideLoading()
		})
	},
	pickerType(event) {
		this.setData({
			"showPickerType": true,
			// "index_type":event.currentTarget.dataset.index
		})
	},
	// onConfirm(event) {
	//   const {
	//     value
	//   } = event.detail;
	//   const index_type=this.data.index_type
	//   const type="cropList["+index_type+"].type"
	//   console.log(event,'12')
	//   this.setData({
	//     [type]:value,
	//     "showPickerType": false
	//   })
	// },
	// onCancel() {
	//   this.setData({
	//     "showPickerType": false
	//   })
	// },

	//修改农场品采购量
	changweight(e) {
		const index = e.currentTarget.dataset.index
		const demandWeight = "cropList[" + index + "].demandWeight"
		this.setData({
			[demandWeight]: e.detail,
		})
		console.log(this.data.cropList, 2)
	},
	cancelcrops() {
		this.setData({
			showPickerCrop: false
		});
	},
	//确认农产品
	surecrops() {
		var cropList = [];
		this.data.needList.forEach(item => {
			let obj = {
				cropName: item.cropName,
				cropId: item.id,
				demandWeight: '',
			}
			cropList.push(obj)
		})
		console.log('cropList', cropList)
		this.setData({
			cropList
		});
		this.setData({
			showPickerCrop: false
		});
	},
	//农产品选择弹框
	pickerCrops() {
		this.getCrops();
	},
	//获取作物信息
	getCrops() {
		// let obj = {
		// 	classificationIds: [1, 2, 4]
		// }
		wx.$apis.getCropCategoriesByCompanyId(app.globalData.userInfo.companyData.companyId).then(res => {
      let categoryList = res.data.filter((item) => item.varietyId);
		let newList=	categoryList.map(item=>{
			return{
				id:item.varietyId,
				cropName:item.varietyName
			}	
			})
			wx.hideLoading()
			if(newList.length>0){
				this.setData({
					showPickerCrop:true
				})
				}else{
					wx.showToast({
						title: '请先添加营收菜品~',
						icon: 'none',
						duration: 2000
					})
				}
			this.setData({
				list: newList
			})

		}).catch(err => {
			wx.hideLoading()
		})
	},
	onChange(event) {
		let newlist = []
		event.detail.map(kk => {
			let obj = {}
			obj = this.data.list.find((item) => {
				return item.cropName == kk
			})
			newlist.push(obj)
		})
		this.setData({
			needList: newlist,
			result: event.detail,
		});
		console.log('result', this.data.result)
	},

	toggle(event) {
		const { index } = event.currentTarget.dataset;
		const checkbox = this.selectComponent(`.checkboxes-${index}`);
		checkbox.toggle();
	},
	noop(e) { },

	pickerTime() {
		this.setData({
			showPicker: true,
		})
	},
	canceltime() {
		this.setData({
			showPicker: false,
		});
	},
	suretime(event) {
		console.log('event', event)
		this.setData({
			showPicker: false,
			receiptTime: this.timeFormat(event.detail),

		});
	},
	timeFormat(time) { // 时间格式化 2019-09-08
		var time = new Date(time)
		let year = time.getFullYear();
		let month = (time.getMonth() + 1 < 10 ? '0' + (time.getMonth() + 1) : time.getMonth() + 1);
		let day = time.getDate() < 10 ? '0' + time.getDate() : time.getDate();
		return year + '-' + month + '-' + day
	},
	pickerTwiceTareWeight() {
		wx.navigateTo({
			url: '/pages/business/tareweight/index',
		})
	},
	//添加货主
	pickerOwner() {
		wx.navigateTo({
			url: '/pages/order/ownermanagement/ownermanagement?goodsOwnerUserId='+this.data.goodsOwnerUserId,
		})
	},
	//添加农户
	pickerFarmer() {
		wx.navigateTo({
			url: '/pages/order/farmer/farmer',
			success: (res) => {
				res.eventChannel.emit('famerListData', {
					farmerList: this.data.farmerList,
				})
		}
		})
	},
	  //添加包装
		addpick() {
				wx.navigateTo({
					url: '/pages/order/choosepackage/choosepackage',
					success: (res) => {
							res.eventChannel.emit('packListData', {
								packList: this.data.packList,
							})
					}
			})
		},

	//确认提交
	submit() {
		const newJudge = this.data.cropList.filter(item => !item.demandWeight);
		// wx.hideKeyboard();
		let packIds=this.data.packList&&this.data.packList.map(item=>{
			return item.id
		})
		if (!this.data.goodsOwnerUserName) {
			return wx.showToast({
				title: "请选择货主",
				icon: "error",
				duration: 1000
			});
		}
		if (!this.data.receiptTime) {
			return wx.showToast({
				title: "请选择收货时间",
				icon: "error",
				duration: 1000
			});
		}
		if (!packIds.length) {
			return	wx.showToast({
				title: "请选择包装",
				icon: "error",
				duration: 1000
			})
		}
		if (!this.data.cropList.length) {
			return wx.showToast({
				title: "请选择采购农产品",
				icon: "error",
				duration: 1000
			});
		}
		if (newJudge.length) {
			return wx.showToast({
				title: "请填写采购量",
				icon: "error",
				duration: 1000
			});
		}
		let api, obj;
		let farmerUserIds=this.data.farmerList&&this.data.farmerList.map(item=>{
			return item.userId
		})

		let cropList=this.data.cropList.map(item=>{
			return{
				demandWeight:item.demandWeight*1,
				cropId: item.cropId,
				cropName: item.cropName,
			}
		})
		if (this.data.type == 1) {
			//修改接口
			api = "updateOrderList";
			obj = {
				receiptTime: this.data.receiptTime + " 23:59:59",
				details: cropList,
				remarks: this.data.remarks,
				id: this.data.id,
				farmerUserIds:farmerUserIds,
				packIds
			}
		} else {
			api = "createOrder";
			obj = {
				companyId: app.globalData.userInfo.companyData.companyId,
				receiptTime: this.data.receiptTime + " 23:59:59",
				details: this.data.cropList,
				remarks: this.data.remarks,
				goodsOwnerUserId: this.data.goodsOwnerUserId,
				farmerUserIds:farmerUserIds,
				packIds
			}
		}
		wx.$apis[api](obj).then(res => {
			// wx.hideLoading()
			// wx.showToast({
			//   title: '提交成功！',
			//   icon: 'success',
			//   duration: 2000
			// })
			//成功跳转页面
			// wx.switchTab({
			//   url: "/pages/order/index/index",
			//   success: function () {
			//     var page = getCurrentPages().pop();
			//     if (page == undefined || page == null) return;
			//     page.onLoad();
			//   }
			// })
			wx.setStorage({
				key: "back",
				data: true,
				success: function () {
						wx.navigateBack(); //返回上一个页面
				}
			})

		}).catch(err => {
			// wx.hideLoading()
		})
	},

	/**
	 * 生命周期函数--监听页面加载
	 */


	onLoad: function (options) {
		const id = options.id;
		const type = options.type;
		this.setData({
			id,
			type
		})
		// console.log(options, 11111)
		if (id) {
			this.getDetail(id)
			wx.setNavigationBarTitle({
				title: "修改订单计划"
			})
			this.setData({
				flag:true
			})
		}else{
			this.setData({
				flag:false
			})
		}

	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {
		wx.getStorage({
			key: 'ownerInfo',
			success: (res) => {
				// let typeList = this.data.typeList
				// typeList.push(res.data)
				this.setData({
					goodsOwnerUserName: res.data.name,
					goodsOwnerUserId: res.data.id,
				})
				wx.removeStorage({
					key: 'ownerInfo',
				})
			}
		})
		wx.getStorage({
			key: 'farmerData',
			success: (res) => {
				this.setData({
					farmerList:res.data.farmerDataList
				})
				console.log(this.data.farmerList, 'farmerList')
				wx.removeStorage({
					key: 'farmerData',
				})
			}
		})
		wx.getStorage({
      key: 'packageType',
      success: (res) => {
				// let typeList=	JSON.parse(JSON.stringify(res.data.packageTypeList).replace(/name/g, 'packName').replace(/id/g, 'packId'))
				let typeList=res.data.packageTypeList
				console.log(typeList,'typeList')
        if (typeList && typeList.length) {
          this.setData({
            packList: typeList,
          })
        }
        wx.removeStorage({
          key: 'packageType',
        })
      }
    })
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {

	}
})